package com.elecbook.rpc.config;

import com.elecbook.base.util.SecurityUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Primary
@Configuration
@EnableFeignClients(basePackages = {"com.elecbook.rpc.feignclient"})
public class feignclientConfig implements RequestInterceptor {
//    @Bean
//    public RequestInterceptor userInfoRequestInterceptor() {
//        return new RequestInterceptor() {
//            @Override
//            public void apply(RequestTemplate template) {
//                // 获取登录用户
//                Integer userId = SecurityUtil.getCurrentId();
//                if (userId == null) {
//                    // 如果为空则直接跳过
//                    return;
//                }
//                // 如果不为空则放入请求头中，传递给下游微服务
//                template.header("user-info", userId.toString());
//            }
//        };
//    }

    @Override
    public void apply(RequestTemplate template) {
        try {
            // 获取对象
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes();
            if (requestAttributes != null) {
                // 获取请求对象
                HttpServletRequest request = requestAttributes.getRequest();
                // 获取当前请求的header，获取到jwt令牌
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {
                        String headerName = headerNames.nextElement();
                        String headerValue = request.getHeader(headerName);
                        // 将header向下传递
                        template.header(headerName, headerValue);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
